// Copyright (c) 2010 SuccessFactors, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//     * Redistributions of source code must retain the above
//       copyright notice, this list of conditions and the following
//       disclaimer.
//
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials
//       provided with the distribution.
//
//     * Neither the name of the SuccessFactors, Inc. nor the names of
//       its contributors may be used to endorse or promote products
//       derived from this software without specific prior written
//       permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

package org.owasp.jxt;

import java.util.Arrays;
import java.util.List;

/**
 * Expr
 *
 * @author Jeffrey Ichnowski
 * @version $Revision: 8 $
 */
public abstract class JxtExpr {
    JxtExpr() {
    }

    public static JxtExpr createLiteral(String text) {
        return new Literal(text);
    }

    public static JxtExpr createCode(String code) {
        return new Code(code);
    }

    public static JxtExpr createConcat(JxtExpr ... exprs) {
        return new Concat(exprs);
    }

    public abstract boolean isLiteral();
    public abstract boolean isConcatenation();
    public abstract String getText();
    public abstract String toCode(Class<?> targetType);
    public abstract List<? extends JxtExpr> getSubExprs();

    public final String toString() {
        return toCode(String.class);
    }

    static final class Literal extends JxtExpr {
        private String _text;

        Literal(String text) {
            _text = text;
        }

        public boolean isLiteral() {
            return true;
        }

        public String getText() {
            return _text;
        }

        public boolean isConcatenation() {
            return false;
        }

        public List<? extends JxtExpr> getSubExprs() {
            return Arrays.asList(this);
        }

        private static boolean parseBoolean(String str) {
            if ("true".equals(str)) {
                return true;
            } else if ("false".equals(str)) {
                return false;
            } else {
                throw new IllegalArgumentException("invalid boolean value: "+str);
            }
        }

        private static char parseChar(String str) {
            if (str.length() == 1) {
                return str.charAt(0);
            } else {
                throw new IllegalArgumentException("invalid character value: "+str);
            }
        }

        public String toCode(Class<?> targetType) {
            if (targetType == null ||
                targetType == String.class ||
                targetType == Object.class ||
                targetType == CharSequence.class)
            {
                return Encoder.JAVA_STRING.apply(
                    new StringBuilder("\""), _text)
                    .append("\"").toString();
            }

            if (targetType == Boolean.class) {
                return parseBoolean(_text) ? "Boolean.TRUE" : "Boolean.FALSE";
            } else if (targetType == Boolean.TYPE) {
                return parseBoolean(_text) ? "true" : "false";
            } else if (targetType == Integer.class) {
                return "new Integer("+Integer.parseInt(_text)+")";
            } else if (targetType == Integer.TYPE) {
                return String.valueOf(Integer.parseInt(_text));
            } else if (targetType == Long.class) {
                return "new Long("+Long.parseLong(_text)+")";
            } else if (targetType == Long.TYPE) {
                return Long.parseLong(_text) + "L";
            } else if (targetType == Double.class) {
                return "new Double("+Double.parseDouble(_text)+")";
            } else if (targetType == Double.TYPE) {
                return String.valueOf(Double.parseDouble(_text));
            } else if (targetType == Float.class) {
                return "new Float((float)"+Float.parseFloat(_text)+")";
            } else if (targetType == Float.TYPE) {
                return "(float)"+Float.parseFloat(_text);
            } else if (targetType == Short.class) {
                return "new Short((short)"+Short.parseShort(_text)+")";
            } else if (targetType == Short.TYPE) {
                return "(short)"+Short.parseShort(_text);
            } else if (targetType == Character.class) {
                return "new Character(\'"+Encoder.JAVA_STRING.apply(String.valueOf(parseChar(_text)))+"\')";
            } else if (targetType == Character.TYPE) {
                return "\'"+Encoder.JAVA_STRING.apply(String.valueOf(parseChar(_text)))+"\'";
            } else if (targetType == Byte.class) {
                return "new Byte((byte)"+Byte.parseByte(_text)+")";
            } else if (targetType == Byte.TYPE) {
                return "(byte)"+Byte.parseByte(_text);
            }

            throw new IllegalArgumentException("Cannot convert to "+targetType.getName());
        }
    }

    static final class Code extends JxtExpr {
        private String _code;

        Code(String code) {
            _code = code;
        }

        public boolean isLiteral() {
            return false;
        }

        public String getText() {
            return null;
        }

        public boolean isConcatenation() {
            return false;
        }

        public List<? extends JxtExpr> getSubExprs() {
            return Arrays.asList(this);
        }

        public String toCode(Class<?> targetType) {
            return _code;
        }
    }

    static final class Concat extends JxtExpr {
        private JxtExpr[] _exprs;

        Concat(JxtExpr[] exprs) {
            _exprs = exprs;
        }

        public boolean isLiteral() {
            return false;
        }

        public String getText() {
            return null;
        }

        public boolean isConcatenation() {
            return true;
        }

        public List<JxtExpr> getSubExprs() {
            return Arrays.asList(_exprs);
        }

        public String toCode(Class<?> targetType) {
            StringBuilder buf = new StringBuilder();
            String sep = "(";

            for (JxtExpr e : _exprs) {
                buf.append(sep).append(e.toCode(String.class));
                sep = ")+(";
            }

            return buf.append(")").toString();
        }
    }

} // JxtExpr
